package com.UdpRecieve.controller;
import com.UdpRecieve.domain.system.SysUser;
import com.UdpRecieve.framework.ExceptionBusiness.LoginException;
import com.UdpRecieve.framework.constant.ServletConstant;
import com.UdpRecieve.service.SysLoginService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
public class LoginController {

    Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 跳转登录界面
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/login")
    public ModelAndView toLoginPage(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView();
        //判断是否是用户已经登录
        if(sysLoginService.isLogin(request,response)){
            mv.setViewName("redirect:"+ ServletConstant.INDEXPAGE);
        }else {
            mv.setViewName("login");
        }

        return mv;
    }

    /**
     * 登录
     * @param user
     * @param request
     * @param response
     * @param attributes
     * @return
     */
    @PostMapping("/doLogin")
    @ResponseBody
    public ModelAndView doLogin(SysUser user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes attributes){
        ModelAndView mv = new ModelAndView();
        logger.info(user);

        //执行登录操作
        try {
            //检查该用户是否在别的浏览器是否已经登录
            sysLoginService.isLoginOnOtherWeb(user,request,response);
            //登录
            sysLoginService.doLogin(user,request,response);
            mv.setViewName("redirect:"+ ServletConstant.INDEXPAGE);
        }catch (LoginException e){
            attributes.addFlashAttribute("msg",e.getMessage());
            mv.setViewName("redirect:/login");
        }catch (Exception e) {
            attributes.addFlashAttribute("msg",e.getMessage());
            mv.setViewName("redirect:/login");
            e.printStackTrace();
        }
        return mv;
    }


    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/loginOut")
    @ResponseBody
    public ModelAndView loginOut(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView();
        sysLoginService.loginOut(request,response);
        mv.setViewName("redirect:/login");
        return mv;
    }
}
